package com.cgs.query.handler.security

import com.cgs.query.configuration.QueryConfiguration
import com.cgs.query.domain.QuerySource
import com.cgs.query.exception.QueryException
import com.cgs.query.handler.PermissionObject
import com.cgs.query.handler.SecurityAdapter
import com.cgs.query.service.IQueryDefineService
import com.cgs.query.service.IQueryProjectService
import com.cgs.query.service.IQuerySourceService
import mu.KotlinLogging
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import java.lang.reflect.Method
import javax.annotation.PostConstruct
import kotlin.reflect.jvm.reflect

private val logger = KotlinLogging.logger { }

/**
 * 权限检查切面
 */
@Aspect
@ConditionalOnExpression("\${sql.runner.permission:false}")
class SecurityAspect {

    @Autowired
    lateinit var configuration: QueryConfiguration

    @Pointcut("@annotation(com.cgs.query.handler.Permission)")
    fun securityPointCut() {
    }

    @PostConstruct
    fun log() {
        logger.info { "将对@Permission注解进行权限控制" }
    }

    @Around("securityPointCut()")
    @Throws(Throwable::class)
    fun doAround(pjp: ProceedingJoinPoint): Any? {
        val permissionObject = (pjp.target as? SecurityAdapter)?.adapter(pjp.signature.name, pjp.args)
        if (permissionObject != null) {
            configuration.securityHandler?.checkPermission(permissionObject)
        }
        return pjp.proceed()
    }
}